package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.common.SMSUtils;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 移动端用户管理
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信
     */
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        String code = RandomStringUtils.random(4, false, true);
//        SMSUtils.sendSMS(user.getPhone(), code);
        log.info("短信已发送:{}",code);
//        session.setAttribute(phone,code); //session 名称为phone 可以防止 用户获取验证码之后 输入新的手机号 导致违法登录
        redisTemplate.opsForValue().set(phone,code,120, TimeUnit.SECONDS);
        return R.success("验证码已发送");
    }

    /**
     * 验证码登录
     * @return
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map<String,String> map,HttpSession session){
        String phone = map.get("phone");
        String code = map.get("code");
//        String attribute =(String) session.getAttribute(phone);
        String attribute =(String) redisTemplate.opsForValue().get(phone);
        if(!code.equals(attribute)){
            return R.error("密码错误");
        }
        User user = userService.lambdaQuery().eq(User::getPhone, phone)
                .one();
        if(user==null){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
        }
        session.setAttribute("user",user.getId());
        redisTemplate.delete(phone);
        return R.success(user);
    }

    @PostMapping("loginout")
    public R<String> loginOut(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }



}
